package com.czk.yygh.order.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.czk.enums.PaymentTypeEnum;
import com.czk.enums.RefundStatusEnum;
import com.czk.model.order.OrderInfo;
import com.czk.model.order.PaymentInfo;
import com.czk.model.order.RefundInfo;
import com.czk.yygh.order.service.OrderService;
import com.czk.yygh.order.service.PaymentService;
import com.czk.yygh.order.service.RefundInfoService;
import com.czk.yygh.order.service.WeiXinService;
import com.czk.yygh.order.utils.ConstantPropertiesUtils;
import com.czk.yygh.order.utils.HttpClient;
import com.github.wxpay.sdk.WXPayConstants;
import com.github.wxpay.sdk.WXPayUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @Author:ChenZhangKun
 * @Date: 2021/11/30 16:27
 */
@Service
public class WeiXinServiceImpl implements WeiXinService {
    @Autowired
    private OrderService orderService;
    @Autowired
    private PaymentService paymentService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private RefundInfoService refundInfoService;
    @Override
    public Map createNative(Long orderId) {
        // 从redis获取数据
        Map map = (Map) redisTemplate.opsForValue().get(orderId.toString());
        if (map != null) {
            // 还没过期
            return map;
        }
        OrderInfo orderInfo = orderService.getById(orderId);
        // 向记录表添加信息
        paymentService.savePaymentInfo(orderInfo, PaymentTypeEnum.WEIXIN.getStatus());
        // 设置参数，提供微信二维码的参数
        Map paramMap = new HashMap();
        paramMap.put("appid", ConstantPropertiesUtils.APPID);
        paramMap.put("mch_id", ConstantPropertiesUtils.PARTNER);
        paramMap.put("nonce_str", WXPayUtil.generateNonceStr());
        String body = orderInfo.getReserveDate() + "就诊" + orderInfo.getDepname();
        paramMap.put("body", body);
        paramMap.put("out_trade_no", orderInfo.getOutTradeNo());
        // paramMap.put("total_fee", order.getAmount().multiply(new BigDecimal("100")).longValue()+"");
        // 为了测试，统一写成这个值 0.01元
        paramMap.put("total_fee", "1");
        paramMap.put("spbill_create_ip", "127.0.0.1");
        paramMap.put("notify_url", "http://guli.shop/api/order/weixinPay/weixinNotify");
        paramMap.put("trade_type", "NATIVE");
        //4 调用微信生成二维码接口,httpclient调用
        HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/pay/unifiedorder");
        try {
            client.setXmlParam(WXPayUtil.generateSignedXml(paramMap, ConstantPropertiesUtils.PARTNERKEY));
            // 开启https
            client.setHttps(true);
            client.post();
            // 返回相关的数据->xml数据
            String content = client.getContent();
            Map<String, String> resultMap = WXPayUtil.xmlToMap(content);
            // 6 封装返回结果集
            map = new HashMap<>();
            map.put("orderId", orderId);
            map.put("totalFee", orderInfo.getAmount());
            map.put("resultCode", resultMap.get("result_code"));
            // 二维码地址
            map.put("codeUrl", resultMap.get("code_url"));
            if (resultMap.get("result_code") != null) {
                // 设置过期时间
                redisTemplate.opsForValue().set(orderId.toString(), map, 120, TimeUnit.MINUTES);
            }
            return map;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public Map<String, String> queryPayStatus(Long orderId) {
        try {
            // 根据id获取订单信息
            OrderInfo orderInfo = orderService.getById(orderId);
            // 封装提交参数
            Map paramMap = new HashMap();
            // 商户id
            paramMap.put("appid", ConstantPropertiesUtils.APPID);
            paramMap.put("mch_id", ConstantPropertiesUtils.PARTNER);
            paramMap.put("out_trade_no", orderInfo.getOutTradeNo());
            // 随机字符串
            paramMap.put("nonce_str", WXPayUtil.generateNonceStr());
            // 设置请求内容
            HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/pay/orderquery");
            client.setXmlParam(WXPayUtil.generateSignedXml(paramMap, ConstantPropertiesUtils.PARTNERKEY));
            client.setHttps(true);
            client.post();
            // 得到微信返回数据
            String content = client.getContent();
            Map<String, String> resultMap = WXPayUtil.xmlToMap(content);
            System.out.println("支付状态resultMap:" + resultMap);
            //5 把接口数据返回
            return resultMap;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public Boolean refund(Long orderId) {
        // 拿到支付记录信息
        PaymentInfo paymentInfo = paymentService.getPaymentInfo(orderId,PaymentTypeEnum.WEIXIN.getStatus());
        // 加入退款记录表
        RefundInfo refundInfo = refundInfoService.saveRefundInfo(paymentInfo);
        //
        if (refundInfo.getRefundStatus().equals(RefundStatusEnum.REFUND.getStatus())){
            // 已退款
            return true;
        }
        Map<String,String> paramMap=new HashMap<>();
        // 公众账号ID
        paramMap.put("appid",ConstantPropertiesUtils.APPID);
        // 商户编号
        paramMap.put("mch_id",ConstantPropertiesUtils.PARTNER);
        paramMap.put("nonce_str",WXPayUtil.generateNonceStr());
        // 微信订单号
        paramMap.put("transaction_id",paymentInfo.getTradeNo());
        // 商户订单编号
        paramMap.put("out_trade_no",paymentInfo.getOutTradeNo());
        paramMap.put("out_refund_no","tk"+paymentInfo.getOutTradeNo()); //商户退款单号
        paramMap.put("total_fee","1");
        paramMap.put("refund_fee","1");
        HttpClient client=null;
        try {
            String paramXml = WXPayUtil.generateSignedXml(paramMap,ConstantPropertiesUtils.PARTNERKEY);
            // 设置调用接口内容
            client = new HttpClient("https://api.mch.weixin.qq.com/secapi/pay/refund");
            client.setXmlParam(paramXml);
            client.setHttps(true);
            // 设置证书信息
            client.setCert(true);
            client.setCertPassword(ConstantPropertiesUtils.PARTNER);
            client.post();
            String content = client.getContent();
            Map<String, String> resultMap = WXPayUtil.xmlToMap(content);
            // 退款结果
            if (null != resultMap && WXPayConstants.SUCCESS.equalsIgnoreCase(resultMap.get("result_code"))) {
                // 设置退款时间
                refundInfo.setCallbackTime(new Date());
                // 退款序列号
                refundInfo.setTradeNo(resultMap.get("refund_id"));
                // 退款状态
                refundInfo.setRefundStatus(RefundStatusEnum.REFUND.getStatus());
                refundInfo.setCallbackContent(JSONObject.toJSONString(resultMap));
                refundInfoService.updateById(refundInfo);
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return false;
    }
}
